/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-03-25
*/
package com.rzico.basics.controller.admin;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rzico.annotation.Log;
import com.rzico.base.BaseController;
import com.rzico.base.CommResult;
import com.rzico.basics.entity.Enterprise;
import com.rzico.basics.entity.Product;
import com.rzico.basics.service.EnterpriseService;
import com.rzico.basics.service.ProductService;
import com.rzico.entity.PageResult;
import com.rzico.entity.Pageable;
import com.rzico.basics.entity.Coupon;
import com.rzico.basics.service.CouponService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 优惠券控制层
 *
 * @author Rzico Boot
 * @version 1.0
 * @date 2020-03-25
 */
@Api(description = "优惠券接口")
@RestController
@RequestMapping("/admin/coupon")
public class CouponAdminController extends BaseController {

    @Autowired
    private CouponService couponService;

    @Autowired
    private EnterpriseService enterpriseService;

    @Autowired
    private ProductService productService;

    /**
     * 分页查询优惠券
     *
     * @return
    */
    @ApiOperation("分页查询优惠券")
    @GetMapping("/list")
    @ApiImplicitParams({@ApiImplicitParam(name = "startDate", value = "开始时间", dataType = "String", paramType = "query") ,
            @ApiImplicitParam(name = "endDate", value = "结束时间", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "type", value = "活动类型", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "状态（0.待审核，1.已审核，2.已过期）", dataType = "Integer", paramType = "query")
    })
    public CommResult<Coupon> list(Date startDate, Date endDate,Integer type,Integer status, Pageable pageable) {
        Map<String, Object> params = new HashMap<String, Object>();
        params = buildSortField(params, pageable);
        if (startDate!=null){
            params.put("startDate", startDate);
        }
        if (endDate!=null){
            params.put("endDate", DateUtils.addMilliseconds(DateUtils.addDays(endDate,1),-1));
        }


        Enterprise enterprise = enterpriseService.getCurrent();
        if (enterprise!=null) {
            params.put("enterpriseId", enterprise.getId());
        } else {
            return CommResult.error("没有开通企业");
        }

        if (type!=null){
            params.put("type", type);
        }

        if (status!=null){
            params.put("status", status);
        }

        params.put("subType", 0);
        params.put("deleted", false);

        Page<Object> startPage = PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
        List<Coupon> list = couponService.selectList(params);
        PageResult<Coupon> pageResult = new PageResult<Coupon>(list, startPage.getTotal(), pageable);
        return CommResult.success(pageResult);
    }

    /**
     * 查询单条优惠券
     *
     * @return
    */
    @ApiOperation("查询单条优惠券")
    @GetMapping("/find/{id}")
    public CommResult<Coupon> find(@PathVariable String id) {
        Coupon result = couponService.findById(id);

        Map<String,Object> data = new HashMap<>();
        data.put("coupon",result);
        return CommResult.success(data);

    }

    /**
     * 保存优惠券
     *
     * @param coupon
     * @return
     */
    @ApiOperation("保存优惠券")
    @PostMapping("/save")
    public CommResult<Coupon> save(@RequestBody Coupon coupon) {
        Enterprise enterprise = enterpriseService.getCurrent();
        if (enterprise==null) {
            return CommResult.error("没有开通企业");
        }
        coupon.setEnterpriseId(enterprise.getId());
        coupon.setCreateDate(new Date());
        if (coupon.getType().equals(3)) {
            Product product = productService.selectByPrimaryKey(coupon.getProductId());
            if (coupon.getAmount().compareTo(product.getPrice())>0) {
                return CommResult.error("运费不能大于售价");
            }
        }

        if (coupon.getProductId()!=null) {

            Product product = productService.findById(coupon.getProductId());
            coupon.setGoods(product.getGoodsId());

            if (coupon.getType().equals(3)) {
               if (couponService.checkExists(product,null)) {
                   return CommResult.error("兑换券已经存在");
               }
            }

        }
        if (coupon.getStatus()==null) {
            coupon.setStatus(0);
        }
        coupon = couponService.save(coupon);
        Coupon result = couponService.findById(coupon.getId());
        return CommResult.success(result);

    }


    /**
     * 批量删除优惠券
     *
     * @param ids
     * @return
     */
    @Log(desc = "批量删除优惠券", type = Log.LOG_TYPE.DEL)
    @ApiOperation("批量删除优惠券,ids用逗号拼接")
    @PostMapping("/del/{ids}")
    public CommResult<Coupon> del(@PathVariable String ids) {

        couponService.deleteByIds(ids.split(","));
        return CommResult.success();
    }

    /**
     * 更新优惠券
     *
     * @param coupon
     * @return
     */
    @Log(desc = "更新优惠券", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("更新优惠券")
    @PostMapping("/update")
    public CommResult<Coupon> update(@RequestBody Coupon coupon) {
        if (coupon.getType().equals(3)) {
            Product product = productService.selectByPrimaryKey(coupon.getProductId());
            if (coupon.getAmount().compareTo(product.getPrice())>0) {
                return CommResult.error("运费不能大于售价");
            }
        }
        if (coupon.getProductId()!=null) {
            Product product = productService.findById(coupon.getProductId());
            coupon.setGoods(product.getGoodsId());

            if (coupon.getType().equals(3)) {
                if (couponService.checkExists(product,coupon.getId())) {
                    return CommResult.error("兑换券已经存在");
                }
            }
        }
        coupon = couponService.update(coupon);
        Coupon result = couponService.findById(coupon.getId());
        return CommResult.success(result);
    }


    /**
     * 审核状态更新
     *
     * @param coupon
     * @return
     */
    @Log(desc = "审核状态更新", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("审核状态更新")
    @PostMapping("/updateCoupon")
    public CommResult<Coupon> updateCoupon(@RequestBody Coupon coupon) {

        couponService.updateByPrimaryKeySelective(coupon);
        Coupon result = couponService.findById(coupon.getId());
        return CommResult.success(result);

    }

}
